import React, {Component} from 'react';
import { Breadcrumb ,Button ,Table,Col, Row,Icon,Checkbox, Select ,FormControl } from 'tinper-bee';
import {vendorsTrimStr,vendorsDanger,vendorsFmtDate} from 'utils/config.js';
import {initTableData,getProcedureData,getConstructionData,getDropData} from "./workdatausedata.js"
import './index.less';
import App from "../../layout/App";
import DateTime from "./DateTime.jsx"
import ConnectData from "./connectData.jsx"
import ShowTreeToast from '../WorkQuality/ShowTreeToast.jsx'
import CommonModal from './../../components/CommonModal/index.jsx';
const Option = Select.Option;
let dataAll=[];

export default class WorkDataUseData extends Component {
    constructor(props) {
        super(props);
        let _self=this;

        let billType=sessionStorage.getItem("billType");

        this.state={
            pkProject:"",
            billType:"",
            dropData:[],
            flag:true,
            sgjlFlag:false,
            canChoose:false,
            showModal:false,
            pkBill:"",
            nameValue:"",
            productValue: '',
            inspectareaValue:"",
            startTimeValue:"",
            endTimeValue:"",
            startTime:"",
            endTime:"",
            focusflag:true,
            projectName:"",
            showTree: false,
            iconCloseShow:false,
            pkProcedure:"",
            procedurePkArr:[],
            checkedAll:false,
            cancelState:false,
            needData:{
                projectName:"",
                creatorName:"",
                acceptorName:"",
                creationtime:"",
                inspectarea:"",
                procedureName:"",
            },
            recorddata:{
                inspectstandardName:"",
                processName:"",
                check_object:""
            },
            columns:[
                { title: "序号", dataIndex: "sequence", key: "sequence",width:"40"},
                { title: "制单日期", dataIndex: "billcreationtime", key: "creationtime",width:"60"},
                { title: "制单人", dataIndex: "creatorName", key: "creatorName" ,width:"50"},
                { title: "工序", dataIndex: "procedureName", key: "procedureName" ,width:"195"},
                { title: "检查部位", dataIndex: "inspectarea", key: "inspectarea" ,width:"195"},
                { title: (billType=='SGJL'?"检查标准":"验收人"), dataIndex: (billType=='SGJL'?"inspectStandardName":"acceptorName"), key: "acceptorName" ,width:"60"},
                { title: (billType=='SGJL'?"合格率":"验收结果"), dataIndex: "result", key: "result",width:"60"},
                { title: "操作", dataIndex: "d", key: "d",width:"60" ,
                    render(text, record, index) {
                        return(
                            <div style={{color:"#2C7EDC",cursor: "pointer"}} onClick={()=>{_self.handleShowModel(record)}}>预览</div>
                        )
                } },
            ],
            procedureColumns:[
                { title: "序号", dataIndex: "sequence", key: "sequence",width:"50"},
                { title: "制单人", dataIndex: "record_creator_name", key: "record_creator_name",width:"55" },
                { title: "制单日期", dataIndex: "record_creationtime", key: "record_creationtime",width:"75" },
                { title: "检查部位", dataIndex: "check_object", key: "check_object",width:"250" },
                { title: "质量标准", dataIndex: "inspectstandardName", key: "inspectstandardName" ,width:"60"},
                { title: "图片数量", dataIndex: "picCount", key: "picCount",width:"60" },
                { title: "操作", dataIndex: "d", key: "d",width:"40" ,
            render(text, record, index) {
            return(
                <div style={{color:"#2C7EDC", cursor: "pointer"}} onClick={()=>{_self.handleProcedureClick(record)}}>查看</div>
            )
        } },
        ],
            seachValueGroup:{
                    pkProject:"",
                    billType:"",
                    creator:"",
                    pkProcedure:"",
                    inspectarea:"",
                    startTime:"",
                    endTime:""
            },
            tableProcedureData:[],
            tableData:[],
            sgjlData:[],
        }
    }
    componentDidMount(){
        let pkProject=sessionStorage.getItem("pkProject");
        let billType=sessionStorage.getItem("billType");
        // pkProject="c70d1782-0751-4ac3-b955-58d196338abc";
        let projectName=sessionStorage.getItem("projectName");
        let procedurePkArr=JSON.parse(sessionStorage.getItem("procedurePkArr"));
        let getTableData={...this.state.seachValueGroup,billType,pkProject};
        this.setState({seachValueGroup:getTableData,pkProject,projectName,billType,procedurePkArr},()=>{
            this.getInitTableData(this.state.seachValueGroup,"pkBill")
        })
    }
    addNumber=(tableData,pk)=>{
        let data=tableData?tableData:[];
        let procedurePkArr=this.state.procedurePkArr;
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            item["sequence"]=`0${i+1}`;
            item["key"]=item[pk];
            // item["billType"]="SGJL";
            for (let j = 0; j < procedurePkArr.length; j++) {
                let procedurePkArrItem = procedurePkArr[j];
                if(item["pkBill"]==procedurePkArrItem){
                    item["checked"]=true;
                    break;
                }else {
                    item["checked"]=false;
                }
            }
            item["creationtime"]=vendorsFmtDate(item["creationtime"]);
            if (item["sequence"]>9){
                item["sequence"]=`${i+1}`
            }
        }
        this.setState({tableData:data})
    };

    showData=()=>{
        let pkProcedure=this.state.pkProcedure;
        let startTime=this.state.startTime;
        let endTime=this.state.endTime;
        let inspectarea=this.state.inspectareaValue;
        let creator=this.state.nameValue;
        let data=[];

        for(let i=0,j=dataAll.length;i<j;i++){
            let item=dataAll[i];
            if(pkProcedure&&(!item.pkProcedure||(item.pkProcedure!=pkProcedure))){
                continue;
            }
            if(startTime&&(!item.creationtime||(item.creationtime<new Date(startTime.replace(/-/g,'/')).getTime()))){
                continue;
            }
            if(endTime&&(!item.creationtime||(item.creationtime>(new Date(endTime.replace(/-/g,'/')).getTime()+(24*60*60-1)*1000)))){
                continue;
            }
            if(inspectarea&&(!item.inspectarea||(item.inspectarea.toUpperCase().indexOf(vendorsTrimStr(inspectarea).toUpperCase())==-1))){
                continue;
            }
            if(creator&&(!item.creator||(item.creator!=creator))){
                continue;
            }
            data.push(item);
        }

        let len=2;
        if(data.length<10){
            len=1;
        }else if(data.length<100){
            len=2;
        }else if(data.length<1000){
            len=3;
        }else if(data.length<10000){
            len=4;
        }
        data.forEach((cur,index,arr)=>{
            cur.sequence=('000'+(index+1)).substr(-(len));
        })

        let checkedAll=true;
        for(let i=0,j=data.length;i<j;i++){
            if(!data[i].checked){
                checkedAll=false;
                break;
            }
        }

        this.setState({
            tableData:data,
            checkedAll:checkedAll
        })        
    }


    handleProcedureClick=(rec)=>{
        let recorddata={
            inspectstandardName:rec.inspectstandardName,
            processName:rec.processName,
            check_object:rec.check_object
        };
        let param={pkBill:rec["pk_construct_record"]};
        this.setState({flag:false,recorddata},()=>{
            getConstructionData({...param,ieStamp:new Date().getTime(), isAjax:1}).then((res)=>{
                let data=res.data;
                if(data.resultCode=="ok"){
                    this.addNumber2(data.result["inspectitems"],rec["pk_bill"])
                }else {
                    vendorsDanger({text:data.exMsg})
                }

            });
        });
    };
    addNumber2=(tableData)=>{
        let data=tableData?tableData:[];
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            let datasStr="";
            let datas=item["datas"];
            item["sequence"]=`0${i+1}`;
            item["key"]=item["pkBill"];
            item["pictures"]=item["pictures"].length;
            for (let j = 0; j < datas.length; j++) {
                let itemdata = datas[j].toFixed(2);
                datasStr +=itemdata+";"
            }
            item["datas"]=datasStr;
            if (item["sequence"]>9){
                item["sequence"]=`${i+1}`
            }
        }
        this.setState({sgjlData:data})
    };
    getInitTableData=(param,pk)=>{
        initTableData({...param,ieStamp:new Date().getTime(),isAjax:1}).then((res)=>{
            let data=res.data;
            if(data.resultCode=="ok"){
                dataAll=data.result;
                let procedurePkArr=JSON.parse(sessionStorage.getItem("procedurePkArr"));
                dataAll.forEach((cur,index,arr)=>{
                    cur.key=cur.pkBill;
                    cur.billcreationtime=vendorsFmtDate(cur.creationtime);
                    if(procedurePkArr.includes(cur.pkBill)){
                        cur.checked=true;
                    }else{
                        cur.checked=false;
                    }
                })
                console.log(dataAll[0]);
                this.showData();
                //this.addNumber(data.result,pk)
            }
        })
    };
    changeCheck=(value,rec)=>{
        rec["checked"]=value;
        let tableData=this.state.tableData;
        let num=0;
        for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i];
            if(item["checked"]==true){
                num+=1
            }
        }
        if (num==tableData.length){
            this.setState({checkedAll:true})
        }else {
            this.setState({checkedAll:false})
        }
    };
    changeAllCheck=(value)=>{
        let tableData=this.state.tableData;
        let checkedAll=value;
        if (checkedAll){
            for (let i = 0; i < tableData.length; i++) {
                let item = tableData[i];
                item["checked"]=true
            }
            this.setState({tableData,checkedAll})
        }else {
            for (let i = 0; i < tableData.length; i++) {
                let item = tableData[i];
                item["checked"]=false
            }
            this.setState({tableData,checkedAll})
        }
    };
    handleChooseClick=()=>{
        if(this.state.canChoose){
            this.setState({
                canChoose:false
            })
        }else {
            this.setState({
                canChoose:true
            })
        }
    };
    handleJumpCata=()=>{
        this.setState({
            cancelState: false
        });
    };
    getCheckedBills=()=>{
        let billArr=[];
        let tableData=dataAll;
        let billType=this.state.billType;
        for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i];
            let checkState=item.checked;
            if (billType=="SGJL"){
                if(checkState == true){
                    let arrItem={};
                    arrItem["pkBill"]=item.pkBill;
                    // arrItem["procedureName"]=item.procedureName;
                    arrItem["inspectStandardName"]=item.inspectStandardName;
                    arrItem["pkProcedure"]=item.pkProcedure;
                    billArr.push(arrItem)
                }
            }else {
                if(checkState == true){
                    billArr.push(item.pkBill)
                }
            }
        }
        sessionStorage.setItem("procedurePkArr",JSON.stringify(billArr));
        sessionStorage.setItem("fromSubmit","1");        
        window.location.href="./workdatadoc.html"
    }

    handleTrueClick=()=>{
        this.getCheckedBills();
    };
    handleToastClose=()=>{
        console.log(1);
        this.setState({cancelState:true})
    }
    handleTurnClose = () => {
        window.location.href="./workdatadoc.html"
    };
    handleShowModel=(rec)=>{
        let needData={
            projectName:this.state.projectName,
            creatorName:rec.creatorName,
            acceptorName:rec.acceptorName,
            creationtime:rec.billcreationtime,
            inspectarea:rec.inspectarea,
            procedureName:rec.procedureName
        };
        if(rec["billType"]=="SGJL"){
            let param={pkBill:rec["pkBill"]};
            this.setState({
                flag:false,
                sgjlFlag:true,
                showModal:true,
            },()=>{
                getConstructionData(param).then((res)=>{
                    let data=res.data;
                    if(data.resultCode=="ok"){
                        let recorddata={
                            inspectstandardName:data.result["inspectstandard_name"],
                            processName:rec.procedureName,
                            check_object:rec.inspectarea
                        };

                        this.setState({
                            recorddata,
                            needData
                        });
                        this.addNumber2(data.result.inspectitems)
                    }
                });
            });
        }else {
            this.setState({showModal:true,needData},()=>{
                this.getInitProcedureData({pkBill:rec["pkBill"]})
            })
        }

    };
    addNumber1=(tableData)=>{
        let data=tableData?tableData:[];
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            item["sequence"]=`0${i+1}`;
            item["record_creationtime"]=vendorsFmtDate(item["record_creationtime"]);
            if (item["sequence"]>9){
                item["sequence"]=`${i+1}`
            }
        }
        this.setState({tableProcedureData:data})
    };

    getInitProcedureData=(param)=>{
        getProcedureData({...param,ieStamp:new Date().getTime(), isAjax:1}).then((res)=>{
            let data=res.data;
            if(data.resultCode=="ok"){
                this.addNumber1(data.result["bodyVOs"]);
                this.setState({tableProcedureData:this.state.tableProcedureData})
            }
        })
    };
    close=()=> {
        this.setState({
            showModal: false
        });
    };
    open=()=> {
        this.setState({
            showModal: true
        });
    };

    changeFlag=()=>{
        this.setState({flag:true})
    };
    getDrop=(data)=>{
        let Arr=[];
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            let obj={};
            obj["value"]=item["userId"];
            obj["key"]=item["userName"];
            Arr.push(obj)
        }
        return Arr
    };
    initDropData=()=>{
        if (this.state.focusflag){
            this.setState({focusflag:false},()=>{
                getDropData({keyword:"",projectId:this.state.pkProject,ieStamp:new Date().getTime(), isAjax:1}).then((res=>{
                    let data=res.data;
                    if(data.resultCode=="ok"){
                        let dropData=this.getDrop(data.result);
                        this.setState({dropData,focusflag:true});
                    }
                }))
            })
        }

    };
    handleNameChange=(value)=>{
        this.setState({nameValue:value})
    };
    saveStartTime=(time)=>{
        let starttime=vendorsFmtDate(time);
        this.setState({startTimeValue:time,startTime:starttime})
    };
    saveEndTime=(time)=>{
        let endtime=vendorsFmtDate(time);
        this.setState({endTimeValue:time,endTime:endtime})
    };
    handleChange=(e)=>{
        let value=e.target.value;
        this.setState({inspectareaValue:value})
    };
    handleSearch=()=>{
        this.showData();
        // let seachValueGroup={...this.state.seachValueGroup,
        //     pkProcedure:this.state.pkProcedure,
        //     startTime:this.state.startTime,
        //     endTime:this.state.endTime,
        //     inspectarea:this.state.inspectareaValue,
        //     creator:this.state.nameValue};
        // this.setState({seachValueGroup},()=>{
        //     this.getInitTableData(this.state.seachValueGroup);
        // });
    };
    clearSearch=()=>{
        this.setState({
            nameValue:"",
            productValue:"",
            pkProcedure:"",
            inspectareaValue:"",
            startTimeValue:"",
            startTime:"",
            endTimeValue:"",
            endTime:"",
        });
    };
    onShowTree = () => {
        this.setState({showTree: true})
    };
    onCloseTree = () => {
        this.setState({showTree: false})
    };
    handleToastSearch=(productValue,pkProcedure)=>{
        this.setState({iconCloseShow:true,productValue,pkProcedure},()=>{
            this.onCloseTree();
        })
    };
    onCloseShow=()=>{
        this.setState({
            iconCloseShow:false,
            productValue:'',
            pkProcedure:''
        })
    };
    renderColumnsMultiSelect=(columns)=> {
            let defaultColumns = [
                {
                    title: (
                        <Checkbox
                            checked={this.state.checkedAll}
                            onChange={this.changeAllCheck}
                        />
                    ),
                    key: "checkbox",
                    dataIndex: "checkbox",
                    width: "25",
                    render: (text, record, index) => {
                        return (
                            <Checkbox
                                className="table-checkbox"
                                checked={record.checked}
                                onChange={(value)=>{this.changeCheck(value,record)}}
                            />
                        );
                    }
                }
            ];
            columns = defaultColumns.concat(columns);

        return columns;
    }
    render() {
        let open=  this.state.dropData.map((item)=>{
            return <Option value={item.value}>{item.key}</Option>
        });
        let columns = this.renderColumnsMultiSelect(this.state.columns);
        return (
            <App>
                <div className="workusedata">
                    <div className="workusedata__header">
                        <div className="workusedata__header__left">
                            <Breadcrumb>
                                <Breadcrumb.Item  active>
                                    资料列表
                                </Breadcrumb.Item>
                                <Breadcrumb.Item active>
                                    添加资料
                                </Breadcrumb.Item>
                                <Breadcrumb.Item active>
                                    关联资料
                                </Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                    </div>
                    <div className="workusedata__content">
                        <div className="workusedata__content__header">
                            <div className="workusedata__left">
                                {this.state.billType=="GXBY"?"工序报验列表":"施工记录列表"}
                            </div>
                            <div className="workusedata__right">
                                <Button colors="primary" onClick={this.handleTrueClick}>确定</Button>
                                <Button className="close" onClick={this.handleToastClose}>取消</Button>
                            </div>
                            <CommonModal show={this.state.cancelState}
                                         cancel={this.handleJumpCata}
                                         confirm={this.handleTurnClose}
                                         content={'一旦执行，所填信息将会丢失！是否确认？'}
                                         backdrop={false}
                                         bindCancel={true}
                            />
                        </div>
                        <div className="workusedata__content__serachgroup">
                            <div className="workusedata__serachgroup__header">
                                <div className="workusedata__serachgroup__left">
                                    <span>项目:&ensp;</span>
                                    <span>{this.state.projectName}</span>
                                </div>
                                <div className="workusedata__serachgroup__right"
                                     onClick={this.handleChooseClick}
                                >
                                    筛选条件
                                    {this.state.canChoose?<Icon type="uf-treearrow-down" className="down" />:<Icon type="uf-gridcaretarrowup" className="up" />}
                                </div>
                            </div>
                            {
                                this.state.canChoose?<div className="workusedata--serachgroup">
                                    <Row>
                                        <Col md={4} xs={4} sm={4}>
                                            <div className="drop-input">
                                                <span>制单人:&ensp;</span>
                                                <Select
                                                    showSearch
                                                    value={this.state.nameValue}
                                                    optionFilterProp="children"
                                                    onChange={(value)=>{this.handleNameChange(value)}}
                                                    onFocus={this.initDropData}
                                                    notFoundContent={"没有找到相关条目"}
                                                    allowClear={true}
                                                >
                                                    {open}
                                                </Select>
                                            </div>
                                        </Col>
                                        <Col md={4} xs={4} sm={4}>
                                            <div className="itemgroup clearfix">
                                                <span className="date">制单开始日期:&ensp;</span>
                                                <DateTime className="date" value={this.state.startTimeValue} saveTime={this.saveStartTime}/>
                                            </div>
                                        </Col>
                                        <Col md={4} xs={4} sm={4}>
                                            <div className="itemgroup clearfix">
                                                <span  className="date">制单结束日期:&ensp;</span>
                                                <DateTime className="date" value={this.state.endTimeValue} saveTime={this.saveEndTime}/>
                                            </div>
                                        </Col>
                                        <Col md={4} xs={4} sm={4}>
                                            <div className="itemgroup">
                                                <span>&ensp;&ensp;工序:&ensp;</span>
                                                <input className="checkLeg"
                                                             value={this.state.productValue}
                                                             onClick={this.onShowTree}
                                                             placeholder='请选择'
                                                />
                                                <Icon type="uf-search" className="serachIcon" onClick={this.onShowTree}/>
                                                {this.state.iconCloseShow?<Icon type="uf-close" className='iconClose' onClick={this.onCloseShow}/>:null}
                                            </div>

                                        </Col>
                                        <Col md={4} xs={4} sm={4}>
                                            <div className="itemgroup">
                                            <span>&ensp;&ensp;&ensp;&ensp;检查部位:&ensp;</span>
                                                <input type="text" className="checkLeg" value={this.state.inspectareaValue} onChange={(e)=>this.handleChange(e)}/>
                                            </div>
                                        </Col>
                                        <Col md={4} xs={4} sm={4}>
                                            <div className="workusedata--serach">
                                                <Button className="clearAll" onClick={this.clearSearch}>
                                                    清空重置
                                                </Button>
                                                <Button colors="primary" onClick={this.handleSearch}>
                                                    搜索
                                                </Button>
                                            </div>
                                        </Col>
                                    </Row>
                                </div>:null
                            }

                        </div>
                        <div className="workusedata__content__table">
                            <Table columns={columns}
                                   data={this.state.tableData}
                                   scroll={{ y: 430 }}
                                   emptyText={() => '暂无数据'}
                                   // bordered={true}
                            ></Table>
                        </div>
                    </div>
                    <ConnectData
                        showModal={this.state.showModal}
                        backdrop={false}
                        size="lg"
                        close={this.close}
                        open={this.open}
                        pkBill={this.state.pkBill}
                        tableData={this.state.tableProcedureData}
                        sgjlData={this.state.sgjlData}
                        columns={this.state.procedureColumns}
                        flag={this.state.flag}
                        sgjlFlag={this.state.sgjlFlag}
                        changeFlag={this.changeFlag}
                        needData={this.state.needData}
                        recorddata={this.state.recorddata}
                    />
                    <ShowTreeToast showModal={this.state.showTree}
                                   onToastSearch={this.handleToastSearch}
                                   close={this.onCloseTree}/>
                </div>
            </App>
        )
    }
};